<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="文档名称" prop="libTitle">
        <el-input v-model="queryParams.libTitle" placeholder="请输入文档名称" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="文档类型" prop="libType">
        <el-select clearable v-model="queryParams.libType" placeholder="请选择">
          <el-option v-for="dict in classList" :key="dict.dictCode" :label="dict.dictLabel"
            :value="dict.dictCode"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上传时间" prop="createTime">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button color="#265DA4" :dark="isDark" icon="Search" @click="handleQuery" v-hasPermi="['manager:knowledgeLibrary:query']">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button color="#265DA4" plain icon="Plus" @click="handleAdd" v-hasPermi="['manager:knowledgeLibrary:add']">新增</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="knowList">
      <el-table-column label="序号" align="left" type="index" width="100" />
      <el-table-column label="文库名称" align="left" prop="libTitle" />
      <el-table-column label="文库类型" align="left" prop="libTypeName" />
      <el-table-column label="备注" align="left" prop="remark" />
      <el-table-column label="上传时间" align="left" prop="createTime" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link style="color:#265DA4;" icon="EditPen" @click="handleDetail(scope.row)"
            >详情</el-button>
          <el-button link style="color:#265DA4;" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:knowledgeLibrary:edit']">修改</el-button>
          <el-button link style="color:#265DA4;" icon="Delete" @click="handleDelete(scope.row, scope.$index)"
            v-hasPermi="['manager:knowledgeLibrary:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 详情对话框 -->
    <el-dialog title="知识文库-详情" v-model="openD" width="780px" append-to-body class="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>知识文库-详情</span>
      </template>
      <el-table :data="fileListD">
        <el-table-column label="序号" align="left" type="index" width="100" />
        <el-table-column label="文件名称" align="left" prop="docName" />
        <el-table-column label="文档类型" align="left" prop="docSuffix" />
        <!-- <el-table-column
          label="文档地址"
          align="left"
          prop="docUrl"
        ></el-table-column> -->
        <el-table-column label="上传时间" align="left" prop="updateTime" />
        <el-table-column label="操作" align="left" width="200">
          <template #default="scope">
            <el-button link style="color:#265DA4;" icon="Edit" @click="handlePreview(scope.row)">预览</el-button>
            <el-button link style="color:#265DA4;" icon="Delete" @click="handleDownload(scope.row, scope.$index)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitFormZ">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body class="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>{{ title }}</span>
      </template>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="100px" class="form-box">
        <el-row>
          <el-col :span="10">
            <el-form-item label="文档名称:" prop="libTitle">
              <el-input v-model="form.libTitle" placeholder="请输入文档名称" class="inputDeep" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文档类型:" prop="libType">
              <el-select v-model="form.libType" placeholder="请选择">
                <el-option v-for="dict in classList" :key="dict.dictCode" :label="dict.dictLabel"
                  :value="dict.dictCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="description" label="上传文件:">
              <!-- <el-upload
                class="avatar-uploader"
                action=""
                :http-request="httpRequest"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="el-icon-plus avatar-uploader-icon">
                  <Plus />
               </el-icon>
              </el-upload> -->
              <el-upload :show-file-list="false" action="" :http-request="httpRequest" multiple
                :on-preview="handlePreview">
                <el-button color="#265DA4">上传文件</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="upload-file">
            <el-table border :data="fileList">
              <el-table-column label="序号" align="left" type="index" width="100" />
              <el-table-column label="文件" align="left" prop="name" />
              <!-- <el-table-column label="文件路径" align="left" prop="url" /> -->
              <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link style="color:#265DA4;" icon="Delete" @click="handleDel(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注:" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitForm">确 定</el-button>
          <el-button @click="cancel" color="#265DA4" plain>取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 预览上传的文件 -->
    <el-dialog v-model="preview" width="780px" append-to-bodyclass="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>{{ title }}</span>
      </template>
      <vue-office-docx v-if="previewType === 'doc' || previewType === 'docx'" :src="previewUrl" />
      <vue-office-pdf v-if="previewType === 'pdf'" :src="previewUrl" />
      <vue-office-excel style="height: 600px" v-if="previewType === 'xlsx'" :src="previewUrl" />
      <img v-if="previewType === 'png' || previewType === 'jpg'" :src="previewUrl" alt="" />
    </el-dialog>

  </div>
</template>

<script setup name="Library">
import VueOfficeDocx from "@vue-office/docx";
import "@vue-office/docx/lib/index.css";
import VueOfficeExcel from "@vue-office/excel";
import "@vue-office/excel/lib/index.css";
import VueOfficePdf from "@vue-office/pdf";

import {
  knowledgeLibraryList,
  knowledgeLibraryRomove,
  knowledgeLibraryAdd,
  knowledgeLibraryEdit,
  ossUpload,
} from "@/api/knowledge/library";
import { libTypeList } from "@/api/knowledge/classification";
const { proxy } = getCurrentInstance();

const classList = ref([]);
const knowList = ref([]);
const fileListD = ref([]);
const dateRange = ref([]);
const open = ref(false);
const openD = ref(false);
const preview = ref(false);
const previewType = ref("");
const previewUrl = ref("");
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const ossIds = ref([]);
const fileList = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + "" },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData",
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    libTitle: undefined,
    libType: undefined,
  },
  rules: {
    libTitle: [
      { required: true, message: "文档标题不能为空", trigger: "blur" },
    ],
    libType: [
      { required: true, message: "文档类型不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);


// 上传文件
function httpRequest(obj) {
  console.log(obj, "fileList", fileList);
  let formData = new FormData();

  formData.append("file", obj.file);
  ossUpload(formData).then((res) => {
    if (res.code == "200") {
      let { fileName, url, ossId } = res.data;

      fileList.value.push({
        url,
        name: fileName,
      });
      ossIds.value.push(ossId);
    }
  });
}

function beforeRemove(uploadFile, uploadFiles) {
  proxy.$modal
    .confirm('是否确认删除"' + uploadFile.name + '"的数据项？')
    .then(function () { })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
/** 查询分类列表 */
function getclassList() {
  libTypeList(queryParams.value).then((response) => {
    classList.value = response.rows;
  });
}
/** 查询知识文库列表 */
function getList() {
  loading.value = true;
  knowledgeLibraryList({
    ...queryParams.value,
    params: {
      beginTime: dateRange.value ? dateRange.value[0] : "",
      endTime: dateRange.value ? dateRange.value[1] : "",
    },
  }).then((response) => {
    knowList.value = response.rows;

    total.value = response.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    noticeId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    noticeContent: undefined,
    status: "0",
  };
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  fileList.value = [];
  open.value = true;
  title.value = "添加";
}
/**详情**/
function handleDetail(row) {
  openD.value = true;
  fileListD.value = row.fileList;
}
/** 预览**/
function handlePreview(row) {
  preview.value = true;
  previewType.value = row.docSuffix;
  previewUrl.value = row.docUrl;
}
/** 下载**/
function handleDownload(row) {
  const link = document.createElement("a");
  link.href = row.docUrl;
  link.setAttribute("download", row.docName);
  link.click();
}
/**修改按钮操作 */
function handleUpdate(row) {
  console.log(row, "row----");
  reset();
  form.value.libId = row.libId;
  form.value.libTitle = row.libTitle;
  form.value.libType = row.libType;
  form.value.remark = row.remark;
  ossIds.value = [];
  if (row.fileList && row.fileList.length) {
    fileList.value = row.fileList.map((item) => {
      return {
        url: item.docUrl,
        name: item.docName,
      };
    });
    row.fileList.forEach((item1) => {
      ossIds.value.push(item1.ossId);
    });
  }
  open.value = true;
  title.value = "修改";
}
function submitFormZ() {
  openD.value = false
}
/** 提交按钮 */
function submitForm() {
  console.log(ossIds.value, "ossIds.value");
  // return
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (ossIds.value.length == 0) {
        proxy.$modal.msgSuccess("请上传知识库文件");
        return;
      }
      form.value.ossIds = ossIds.value;
      if (form.value.libId != undefined) {
        knowledgeLibraryEdit(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        knowledgeLibraryAdd(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row, index) {
  const libId = row.libId;
  proxy.$modal
    .confirm('是否确认删除分类为"' + row.libTitle + '"的数据项？')
    .then(function () {
      return knowledgeLibraryRomove(libId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 删除文件操作 */
function handleDel(row, index) {
  console.log(index, "index---");
  fileList.value.splice(index, 1);
  ossIds.value.splice(index, 1);
}

getList();
getclassList();
</script>
<style scoped lang="scss">
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #265DA4 !important; //修改默认的背景色
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #ccc;
  border-radius: 15px;

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

.upload-file {
  margin: 20px 10px;
}

.form-box {
  :deep(.el-form-item__label) {
    text-align: justify;
    text-align-last: justify;
  }

  .el-form-item label:after {
    content: "";
    display: inline-block;
    width: 100%;
  }

}

.inputDeep {
  :deep(.el-input__inner) {
    width: 192px !important;
  }
}
</style>

